import React, { useContext, useEffect } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { Badge, Menu } from 'antd'
import { routeShownArr } from '../Routes'
import { CountContext } from './context/cartItemCount'
import { getItemCount } from '../hooks/cart'

const isActive = (currPath: string, path: string): string => {
    return currPath === path ? 'ant-menu-item-selected' : ''
}
const hideListPath = ['/create/category', '/create/product', '/product/:productId', '/paysuccess']


const Nav = (props: any) => {
    const [count, setCount] = useContext(CountContext)

    // 只要有数据更新，都对购物车数量进行更新
    useEffect(() => {
        setCount(getItemCount())
    })


    return (
        <Menu mode="horizontal" selectable={false}>
            {
                routeShownArr().filter(routeItem => {
                    return !hideListPath.includes(routeItem.path)
                }).map(route => {
                    return <Menu.Item className={isActive(props.location.pathname, route.path)} key={route.path}>
                        <Link to={route.path}>
                            {route.name}
                            {
                                route.name === '购物车' && <Badge count={count} offset={[5, -10]} />
                            }
                        </Link>
                    </Menu.Item>
                })
            }
        </Menu>
    )
}

export default withRouter(Nav)
